# Author: Chris Moyer
from marajo.appengine.handlers import RequestHandler
from marajo.appengine.handlers.db import DBHandler
from marajo.appengine.api.users import User
from marajo.appengine.ext.webapp import template
import marajo.utils

import logging
log = logging.getLogger("marajo.user_handler")

class UserHandler(DBHandler):
	"""A user manipulation handler"""

	def post(self):
		"""Overload to allow you to reset their password"""
		if (self.request.POST.get("action", None) == "reset_pw"):
			u = self.reset_pw(self.read())
			return self.redirect("%s/%s" % (self.request.script_name, u.id))
		else:
			return DBHandler.post(self)

	def create(self, params):
		"""Create a new user
		This allows the requester to send an
		activation email"""
		template_values = {}

		id = params.get("id", "").strip()
		if id == "":
			id = None
		username = params.get("username").strip()
		email = params.get("email").strip()
		nickname = params.get("nickname").strip()
		auth_groups = params.get("auth_groups").strip()
		password = params.get("password")
		if not password:
			password = marajo.utils.genPassword()
			u = User(id=id)
			u.username = username
			u.email = email
			u.password = password
			u.nickname = nickname
			u.put()
			link = "%s/_ah/login?username=%s" % (self.host_url, u.username)
			msg = template.render("activation_email.tmpl", {"activation_link": link, "password": password, "username": u.username})
			u.notify(subject="Account Activation", html_body=msg)
			log.info("Sending account creation email for: %s" % email)
			return u
		elif password != params.get("password_verify"):
			template_values['username'] = username
			template_values['email'] = email
			template_values['nickname'] = nickname
			template_values['auth_groups'] = auth_groups

			return False
		else:
			u = User(id=id)
			u.username = username
			u.email = email
			u.nickname = nickname
			u.auth_groups = auth_groups.split(' ')
			u.password = password
			u.put()
			log.info("[%s] ADD USER %s" % (self.user, u))
			return u

	def reset_pw(self, u):
		"""Generate a random password and email it to this user"""
		password = marajo.utils.genPassword()
		u.password = password
		u.put()
		link = "%s/_ah/login?username=%s" % (self.host_url, u.username)
		msg = template.render("activation_email.tmpl", {"activation_link": link, "password": password, "username": u.username})
		u.notify(subject="Account Activation", body=msg)
		log.info("Sending account creation email for: %s" % u.email)
		return u

class AccountPage(RequestHandler):
	"""The "My Account" page"""

	def get(self):
		return self.display("account.tmpl", {"janrain_url": marajo.conf.get("janrain", "url")})

	def post(self):
		"""Make changes to your own account"""
		password = self.request.POST.get("password", "")
		if password and password == self.request.POST.get("verify_password"):
			self.user.password = password
		nickname = self.request.POST.get("nickname")
		if nickname:
			self.user.nickname = nickname
		email = self.request.POST.get("email")
		if email:
			self.user.email = email

		# Attach a JanRain OID
		token = self.request.POST.get("token")
		if token:
			from marajo.appengine.api.users.janrain import User as JanRainUser
			jr_user = JanRainUser(token)
			if not jr_user.id in self.user.oids:
				self.user.oids.append(jr_user.id)
		self.user.put()
		return self.get()

